#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QFile>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setLayout(ui->verticalLayout);
    //信号connect
    QObject::connect(ui->btnOpen,SIGNAL(clicked(bool)),this,SLOT(on_btnOpen_clicked));

    //lambda表达式
    QObject::connect(ui->btnSave,&QPushButton::clicked,[=](){
        cout << "save btn clicked"<<endl;
        QString plainText = ui->textEdit->toPlainText();
        qDebug() << "纯文本内容：" << plainText;
    });
    //指针方式
    QObject::connect(ui->copyright,&QPushButton::clicked,this,&MainWindow::on_btnCopyRight_clicked);
    QObject::connect(this,SIGNAL(mySignel()),this,SLOT(myslot()));
    QObject::connect(this,SIGNAL(mySignelParams(int)),this,SLOT(mySlotParams(int)));

    emit mySignel();
    emit mySignelParams(5);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_btnClose_clicked()
{
    cout << "close btn clicked"<<endl;
}
void MainWindow::on_btnOpen_clicked() {

    // QFileDialog dialog;
   QString filePath = QFileDialog::getOpenFileName(this,
                                            tr("Open Text"), "/", tr("Text Files (*.txt)"));
    // QString filePath = "/Users/yh/Desktop/12.txt";

    // Open file (Read + Write + Text mode)
    QFile file(filePath);
    if (!file.open(QIODevice::ReadWrite | QIODevice::Text)) {
        qDebug() << "Failed to open file!";
        return;
    }

    // Read existing content (auto-detect encoding)
    QTextStream in(&file);
    while(!in.atEnd()){
        QString content = in.readLine();
        qDebug()<<content;
        ui->textEdit->append(content);  // 覆盖写入
    }


    file.close();
}

void MainWindow::on_btnCopyRight_clicked()
{
    cout << "copyright btn clicked"<<endl;
}

void MainWindow::myslot()
{
    cout << "mysolt is emited"<<endl;
}

void MainWindow::mySlotParams(int value)
{
    cout << "mySlotParams is: "<<value <<endl;
    qDebug()<<"mySlotParams is: "<<value;
}
